package cn.ticket.controller;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.ticket.dao.BusesMapper;
import cn.ticket.model.Buses;
import cn.ticket.model.Busorder;
import cn.ticket.model.Constants;
import cn.ticket.model.Refundlog;
import cn.ticket.model.Relatives;
import cn.ticket.model.Staff;
import cn.ticket.model.Ticketorder;
import cn.ticket.service.BusOrderService;
import cn.ticket.service.BusesService;
import cn.ticket.service.RefundLogService;
import cn.ticket.service.RelativesService;
import cn.ticket.service.StaffService;
import cn.ticket.service.TicketOrderService;
import cn.ticket.service.Utility;

@Controller
@RequestMapping("ticketOrder")
public class TicketOrderController {
	@Autowired
	private TicketOrderService ticketOrderService;
	@Autowired
	private StaffService staffService;
	@Autowired
	private BusesService busesService;
	@Autowired
	private BusOrderService busOrderService;
	@Autowired
	private RefundLogService refundLogService;
	@Autowired
	private RelativesService relativesService;
	private static Log logger = LogFactory.getLog(TicketOrderController.class);

	/*
	 * 手机端订票接口
	 */
	@RequestMapping(value = "insert", method = RequestMethod.POST, produces = { "application/json;charset=utf-8" })
	@ResponseBody
	public String insert(@RequestBody Map<String, String> args) {
		Map<String, Object> result = new HashMap<>();
		String phone = args.get("phone");
		// phone=phone.toUpperCase();
		String password = args.get("password");
		String seatNumber = args.get("seatNumber");
		String seatName = args.get("seatName");
		String busId = args.get("busId");
		String staffId = args.get("staffId");
		Byte type = 0;
		Staff staff = staffService.validateStaff(phone, password);
		if (staff == null || staff.getId() != Integer.parseInt(staffId)) {
			result.put("status", 1002);
			result.put("message", "登录账户验证失败");
			return Utility.gson.toJson(result);
		}
		if (staff.getIseabled() == false) {
			result.put("status", 1002);
			result.put("message", "用户订票权限已被冻结,请联系科室主任或管理员");
			return Utility.gson.toJson(result);
		}

		// 如果退休职工订票
		if (staff.getStatus().equals("4")) {
			if (staff.getOwncount() > 23 || staff.getRelativecount() > 23) {
				result.put("status", 1002);
				result.put("message", "离退休职工订票已达到最大次数!");
				return Utility.gson.toJson(result);
			}
		}
		// 如果亲属乘坐
		List<Relatives> relatives = null;
		if (!staff.getName().equals(seatName)) {
			type = 1;
			relatives = relativesService.getByStaffIdAndName(staff.getId(), seatName);
			//如果亲属非职工且达到最大订票次数
			if (relatives.get(0).getTicketcount() > 23&&relatives.get(0).getIsstaff()==false) {
				result.put("status", 1002);
				result.put("message", "亲属 " + relatives.get(0).getName() + " 订票已达到最大次数!");
				return Utility.gson.toJson(result);
			}
			//如果亲属无订票权限
			if (relatives.get(0).getIseabled()==false) {
				result.put("status", 1002);
				result.put("message", relatives.get(0).getRelative() + relatives.get(0).getName() + "无订票权限!");
				return Utility.gson.toJson(result);
			}
		}
		synchronized (this) {
			Buses buses = busesService.selectByPrimaryKey(Integer.parseInt(busId));
			Busorder busorder = busOrderService.selectByPrimaryKey(buses.getBusorderid());

			Date departureDate = busorder.getDeparturedate();

			if (buses.getRouteid() > 9 && busorder.getEndbusdate().getTime() - (new Date()).getTime() < 0) {
				result.put("status", 1002);
				result.put("message", "已过登记时间!");
				return Utility.gson.toJson(result);
			}
			if ((new Date()).getTime() > (departureDate.getTime() - 1000 * 60 * Constants.TicketStopMins)) {
				result.put("status", 1002);
				result.put("message", "已过订票时间");
				return Utility.gson.toJson(result);
			}
			if (staff.getLastrefunddate() != null && (1000 * 60 * Constants.minTicketInterval) > ((new Date()).getTime()
					- staff.getLastrefunddate().getTime())) {
				result.put("status", 1002);
				result.put("message", "离上次退票时间低于" + Constants.minTicketInterval + "分钟!请稍后订票.");
				return Utility.gson.toJson(result);
			}
//			if (Integer.parseInt(seatNumber) > 49 || Integer.parseInt(seatNumber) < 1) {
//				result.put("status", 1002);
//				result.put("message", "座号超出限制");
//				return Utility.gson.toJson(result);
//			}
			List<Map<String, Object>> ticketorderResult = ticketOrderService
					.getSeatInfoByStaffIdAnd(Integer.parseInt(staffId), seatName, busorder.getId());
			if (!ticketorderResult.isEmpty()) {
				result.put("status", 1002);
				result.put("message",
						"重复订票!当前乘坐人 " + seatName + " 已预定了本次行程 " + ticketorderResult.get(0).get("busNumber") + " 号车 "
								+ ticketorderResult.get(0).get("seatNumber") + "号座,如需更换班车或座位请使用换坐功能或取消原来的订票!");
				return Utility.gson.toJson(result);
			}

			Ticketorder ticketorder = new Ticketorder();
			ticketorder.setBusesid(buses.getId());
			ticketorder.setType(type);
			ticketorder.setBusorderid(busorder.getId());
			ticketorder.setSeatname(seatName);
			ticketorder.setStaffid(staff.getId());
			ticketorder.setSeatnumber((byte) Integer.parseInt(seatNumber));
			int num=0;
			try {
				num = ticketOrderService.insertSelective(ticketorder);
			} catch (Exception e) {
				// TODO: handle exception
				result.put("status", 1002);
				result.put("message", "订票失败,可能此座位已经有人了!");
				return Utility.gson.toJson(result);
			}
		
			if (num == 1) {
				buses.setOccupation((short) (buses.getOccupation() + 1));
				busesService.seatOccupationAdd1(buses.getId());
			
				busorder.setOccupation((short) (busorder.getOccupation() + 1));
				if (staff.getName().equals(seatName)) {
					staff.setOwncount(staff.getOwncount() + 1);
				} else {
					staff.setRelativecount(staff.getRelativecount() + 1);
				}
				int busesCountOrign = busesService.getByBusOrderId(busorder.getId()).size();
				int busesCount = busorder.getBusescount();
				// auto generate bus chengdu
				int busNumber = buses.getNumber();
				if (buses.getOccupation() > 45 && busorder.getOrientation() == 0
						&& busorder.getEndbusdate().getTime() > new Date().getTime()) {

					//
					// //生成5号车
					// if (4 == busNumber && busesCount == 4) {
					// Buses bus = new Buses();
					// bus.setBusorderid(busorder.getId());
					// bus.setRouteid((short) 4);
					// bus.setNumber((byte) (4 + 1));
					// busorder.setBusescount((byte) (busorder.getBusescount() +
					// 1));
					// busorder.setSeatscount((short) (busorder.getSeatscount()
					// + 47));
					// busesService.insertSelective(bus);
					// logger.info("生成成都方向" + bus.getNumber() + "号车;由" +
					// staff.getId() + staff.getName() + "在定下座位"
					// + seatNumber + "时生成");
					//
					// }
					
					// 生成去成都的6号车
					List<Buses> buses2 = busesService.getByBusorderidAndRouteid(busorder.getId(), (byte) 4);
					if ((buses2.get(0).getOccupation() + buses2.get(1).getOccupation()) > 92 && busesCount == Constants.chengduGenerateCarCount
							&& busorder.getOccupation() > Constants.chengduGenerateCount) {
						// Buses bus4=
						Buses bus = new Buses();
						bus.setBusorderid(busorder.getId());
						bus.setRouteid((short) 4);
						bus.setNumber((byte) (5 + 1));
						busorder.setBusescount((byte) (busorder.getBusescount() + 1));
						busorder.setSeatscount((short) (busorder.getSeatscount() + 47));
						busesService.insertSelective(bus);
						logger.info("生成成都方向" + bus.getNumber() + "号车;由" + staff.getId() + staff.getName() + "在定下座位"
								+ seatNumber + "时生成");

					}
				}

				// 生成候车登记车辆
				// if
				// (busorder.getOccupation()>Constants.RegistorGenerator&&busesCount==6&&busorder.getEndbusdate().getTime()-(new
				// Date()).getTime()>0) {
				if (busorder.getOccupation() > Constants.RegistorGenerator && busesCountOrign == busesCount
						&& busorder.getEndbusdate().getTime() - (new Date()).getTime() > 0) {
					Buses bus = new Buses();
					if (busorder.getOrientation() == 0) {
						bus.setBusorderid(busorder.getId());
						bus.setRouteid((short) 11);
						bus.setNumber((byte) (9));
						bus.setSeatcount((short) 60);
					} else if(busorder.getOccupation()>(Constants.RegistorGenerator+15)){
						bus.setBusorderid(busorder.getId());
						bus.setRouteid((short) 10);
						bus.setNumber((byte) (9));
						bus.setSeatcount((short) 60);
					}
					busesService.insertSelective(bus);
				}

				// auto generate bus jidi
				if (buses.getOccupation() > 45 && busorder.getOrientation() == 1 && busNumber > 4
						&& busorder.getEndbusdate().getTime() > (new Date()).getTime()) {

					Buses bus4 = busesService.getByBusorderidAndRouteid(busorder.getId(), (byte) 8).get(0);
					if (busNumber == 5 && busesCount == Constants.jidiGenerateCarCount && bus4.getOccupation() > Constants.jidiGenerateRaoquan4
							&& busorder.getOccupation() > Constants.jidiGenerateCount) {
						Buses bus = new Buses();
						bus.setBusorderid(busorder.getId());
						bus.setRouteid((short) 9);
						bus.setNumber((byte) 6);
						busorder.setBusescount((byte) (busorder.getBusescount() + 1));
						busorder.setSeatscount((short) (busorder.getSeatscount() + 47));
						busesService.insertSelective(bus);
						logger.info("生成基地方向" + bus.getNumber() + "号车;由" + staff.getId() + staff.getName() + "在定下座位"
								+ seatNumber + "时生成");
					}
				}
				busOrderService.updateByPrimaryKeySelective(busorder);
				staffService.updateByPrimaryKey(staff);
				// 亲属订票的话,增加订票次数
				if (relatives != null) {
					relatives.get(0).setTicketcount(relatives.get(0).getTicketcount() + 1);
					relativesService.updateByPrimaryKeySelective(relatives.get(0));
				}				
				result.put("status", 1001);
				result.put("message", "订票成功! 车号:" + buses.getNumber() + " 座位号:" + seatNumber + " 乘坐人:" + seatName);
				return Utility.gson.toJson(result);
			} else {
				result.put("status", 1002);
				result.put("message", "订票失败!");
				return Utility.gson.toJson(result);
			}
		}
	}

	/*
	 * 车队订票接口
	 */
	@RequestMapping(value = "adminInsert", method = RequestMethod.POST, produces = { "application/json;charset=utf-8" })
	@ResponseBody
	public String adminInsert(@RequestBody Map<String, String> args) {
		Map<String, Object> result = new HashMap<>();
		String phone = args.get("phone");
		String password = args.get("password");
		String seatNumber = args.get("seatNumber");
		String seatName = args.get("seatName");
		String busId = args.get("busId");
		String staffId = args.get("staffId");
		Byte type = 2;
		Staff staff = staffService.validateStaff(phone, password);
		if (staff == null || staff.getId() != Integer.parseInt(staffId)) {
			result.put("status", 1002);
			result.put("message", "登录账户验证失败");
			return Utility.gson.toJson(result);
		}
		if (staff.getIseabled() == false) {
			result.put("status", 1002);
			result.put("message", "用户订票权限已被冻结,请联系科室主任或管理员");
			return Utility.gson.toJson(result);
		}

		Buses buses = busesService.selectByPrimaryKey(Integer.parseInt(busId));
		Busorder busorder = busOrderService.selectByPrimaryKey(buses.getBusorderid());

		if (Integer.parseInt(seatNumber) > 49 || Integer.parseInt(seatNumber) < 1) {
			result.put("status", 1002);
			result.put("message", "座号超出限制");
			return Utility.gson.toJson(result);
		}
		if (busorder.getDeparturedate().getTime() < (new Date()).getTime()) {
			result.put("status", 1002);
			result.put("message", "已超过订票时间,请检查所定车次");
			return Utility.gson.toJson(result);
		}
		List<Map<String, Object>> ticketorderResult = ticketOrderService
				.getSeatInfoByStaffIdAnd(Integer.parseInt(staffId), seatName, busorder.getId());
		if (!ticketorderResult.isEmpty()) {
			result.put("status", 1002);
			result.put("message", "重复订票!当前乘坐人" + seatName + "已预定了本次行程 " + ticketorderResult.get(0).get("busNumber")
					+ " 号车" + ticketorderResult.get(0).get("seatNumber") + "号座,如需更换班车或座位请先取消原来的订票!");
			return Utility.gson.toJson(result);
		}
		Ticketorder ticketorder = new Ticketorder();

		ticketorder.setBusesid(buses.getId());
		ticketorder.setBusorderid(busorder.getId());
		ticketorder.setSeatname(seatName);
		ticketorder.setType(type);
		ticketorder.setStaffid(staff.getId());
		ticketorder.setSeatnumber((byte) Integer.parseInt(seatNumber));

		int num = ticketOrderService.insertSelective(ticketorder);
		if (num == 1) {

			buses.setOccupation((short) (buses.getOccupation() + 1));
			busorder.setOccupation((short) (busorder.getOccupation() + 1));
			if (staff.getName().equals(seatName)) {
				staff.setOwncount(staff.getOwncount() + 1);
			} else {
				staff.setRelativecount(staff.getRelativecount() + 1);
			}
			int busesCount = busesService.getByBusOrderId(busorder.getId()).size();
			// auto generate bus chengdu
			int busNumber = buses.getNumber();
			if (buses.getOccupation() > 45 && busorder.getOrientation() == 0 && busNumber > 3
					&& busorder.getEndbusdate().getTime() > new Date().getTime()) {

				// 生成5号车
				// if (4 == busNumber && busesCount == 4) {
				// Buses bus = new Buses();
				// bus.setBusorderid(busorder.getId());
				// bus.setRouteid((short) 4);
				// bus.setNumber((byte) (4 + 1));
				// busorder.setBusescount((byte) (busorder.getBusescount() +
				// 1));
				// busorder.setSeatscount((short) (busorder.getSeatscount() +
				// 47));
				// busesService.insertSelective(bus);
				// logger.info("生成成都方向" + bus.getNumber() + "号车;由" +
				// staff.getId() + staff.getName() + "在定下座位"
				// + seatNumber + "时生成");
				//
				// }
				// 生成6号车
				List<Buses> buses2 = busesService.getByBusorderidAndRouteid(busorder.getId(), (byte) 4);
				if ((buses2.get(0).getOccupation() + buses2.get(1).getOccupation()) > 92 && busesCount == 5) {
					// Buses bus4=
					Buses bus = new Buses();
					bus.setBusorderid(busorder.getId());
					bus.setRouteid((short) 4);
					bus.setNumber((byte) (5 + 1));
					busorder.setBusescount((byte) (busorder.getBusescount() + 1));
					busorder.setSeatscount((short) (busorder.getSeatscount() + 47));
					busesService.insertSelective(bus);
					logger.info("生成成都方向" + bus.getNumber() + "号车;由" + staff.getId() + staff.getName() + "在定下座位"
							+ seatNumber + "时生成");

				}
			}

			// auto generate bus jidi
			if (buses.getOccupation() > 45 && busorder.getOrientation() == 1 && busNumber > 4
					&& busorder.getEndbusdate().getTime() > new Date().getTime()) {
			

				if (busNumber == 5 && busesCount == 5) {
					Buses bus = new Buses();
					bus.setBusorderid(busorder.getId());
					bus.setRouteid((short) 9);
					bus.setNumber((byte) (6));
					busorder.setBusescount((byte) (busorder.getBusescount() + 1));
					busorder.setSeatscount((short) (busorder.getSeatscount() + 47));
					busesService.insertSelective(bus);
					logger.info("生成基地方向" + bus.getNumber() + "号车;由" + staff.getId() + staff.getName() + "在定下座位"
							+ seatNumber + "时生成");
				}
			
			}
		
			busesService.updateByPrimaryKeySelective(buses);
			busOrderService.updateByPrimaryKeySelective(busorder);
			staffService.updateByPrimaryKey(staff);
			result.put("status", 1001);
			result.put("message", "订票成功! 车号:" + buses.getNumber() + " 座位号:" + seatNumber + " 乘坐人:" + seatName);
			return Utility.gson.toJson(result);
		} else {
			result.put("status", 1002);
			result.put("message", "订票失败!");
			return Utility.gson.toJson(result);
		}
	}

	/*
	 * 手机退票接口
	 * 
	 */
	@RequestMapping(value = "delete", method = RequestMethod.POST, produces = { "application/json;charset=utf-8" })
	@ResponseBody
	public String delete(@RequestBody Map<String, String> args) {
		Map<String, Object> result = new HashMap<>();
		String phone = args.get("phone");
		// phone=phone.toUpperCase();
		String password = args.get("password");
		String seatNumber = args.get("seatNumber");
		String seatName = args.get("seatName");
		String busId = args.get("busId");
		String ticketId = args.get("ticketId");
		String staffId = args.get("staffId");
		String cancelReason = args.get("cancelReason");
		if (cancelReason == null) {
			cancelReason = "";
		}
		Staff staff = staffService.validateStaff(phone, password);
		// Ticketorder
		// ticketorder=ticketOrderService.selectByPrimaryKey(Integer.parseInt(ticketId));
		if (staff == null || staff.getId() != Integer.parseInt(staffId)) {
			result.put("status", 1002);
			result.put("message", "登录账户验证失败");
			return Utility.gson.toJson(result);
		}
		if (staff.getIseabled() == false) {
			result.put("status", 1002);
			result.put("message", "用户订票权限已被冻结,请联系科室主任或管理员");
			return Utility.gson.toJson(result);
		}

		// 如果亲属乘坐
		List<Relatives> relatives = null;
		if (!staff.getName().equals(seatName)) {
			relatives = relativesService.getByStaffIdAndName(staff.getId(), seatName);
		}

		synchronized (this) {
			Buses buses = busesService.selectByPrimaryKey(Integer.parseInt(busId));
			Busorder busorder = busOrderService.selectByPrimaryKey(buses.getBusorderid());
			/*
			 * if (busorder.getDeparturedate().getTime()<new Date().getTime()) {
			 * result.put("status", 1002); result.put("message", "票已使用,无法退票!!");
			 * return Utility.gson.toJson(result); }
			 */
			if (busorder.getDeparturedate().getTime() < new Date().getTime() + 1000 * 60 * Constants.RefundStopMins) {
				result.put("status", 1002);
				result.put("message", "开车前" + Constants.RefundStopMins + "分钟不许退票,请珍惜所内资源,慎重订票!!");
				return Utility.gson.toJson(result);
			}
			if (Integer.parseInt(seatNumber) > 49 || Integer.parseInt(seatNumber) < 1) {
				result.put("status", 1002);
				result.put("message", "座号超出限制");
				return Utility.gson.toJson(result);
			}

			int num = ticketOrderService.deleteByPrimaryKey(Integer.parseInt(ticketId));

			if (num == 1) {
		//		buses.setOccupation((short) (buses.getOccupation() - 1));
				busesService.seatOccupationRemove1(buses.getId());
			//	busorder.setOccupation((short) (busorder.getOccupation() - 1));
				busOrderService.seatOccupationRemove1(busorder.getId());
				if (staff.getName().equals(seatName)) {
					staff.setOwncount(staff.getOwncount() - 1);
				} else {
					staff.setRelativecount(staff.getRelativecount() - 1);
				}
				// 如果不是登记车 才会记录退票时间和次数
				if (buses.getRouteid() < 10) {
					staff.setLastrefunddate(new Date());
					staff.setRefundcount(staff.getRefundcount() + 1);
				}

		//		busesService.updateByPrimaryKeySelective(buses);
		//		busOrderService.updateByPrimaryKeySelective(busorder);
				
				staffService.updateByPrimaryKey(staff);
				Refundlog refundlog = new Refundlog();
				refundlog.setBusesid(buses.getId());
				refundlog.setStaffid(staff.getId());
				refundlog.setSeatname(seatName);
				refundlog.setSeatnumber(Byte.parseByte(seatNumber));
				refundlog.setReason(cancelReason);
				refundLogService.insertSelective(refundlog);
				// 亲属退票的话,更新订票次数
				if (relatives != null && !relatives.isEmpty()) {
					relatives.get(0).setTicketcount(relatives.get(0).getTicketcount() - 1);
					relativesService.updateByPrimaryKeySelective(relatives.get(0));
				}
				if (buses.getRouteid() < 10) {
					
					result.put("message", "退票成功");
				}
				else {
					result.put("message", "成功取消登记");
				}
				
				result.put("status", 1001);
				
				return Utility.gson.toJson(result);
			} else {
				result.put("status", 1002);
				result.put("message", "退票失败!");
				return Utility.gson.toJson(result);
			}
		}
	}

	// 后台退票
	@RequestMapping(value = "deleteByAdmin", method = RequestMethod.POST, produces = {
			"application/json;charset=utf-8" })
	@ResponseBody
	public String deleteByAdmin(@RequestBody Map<String, String> args) {
		Map<String, Object> result = new HashMap<>();
		String phone = args.get("phone");
		// phone=phone.toUpperCase();
		String password = args.get("password");
		String seatNumber = args.get("seatNumber");
		String seatName = args.get("seatName");
		String busId = args.get("busId");
		String ticketId = args.get("ticketId");
		String staffId = args.get("staffId");
		String cancelReason = args.get("cancelReason");
		if (cancelReason == null) {
			cancelReason = "";
		}
		Staff staff = staffService.validateStaff(phone, password);
		// Ticketorder
		// ticketorder=ticketOrderService.selectByPrimaryKey(Integer.parseInt(ticketId));
		if (staff == null || staff.getId() != Integer.parseInt(staffId)) {
			result.put("status", 1002);
			result.put("message", "登录账户验证失败");
			return Utility.gson.toJson(result);
		}
		if (staff.getIseabled() == false) {
			result.put("status", 1002);
			result.put("message", "用户订票权限已被冻结,请联系科室主任或管理员");
			return Utility.gson.toJson(result);
		}

		Buses buses = busesService.selectByPrimaryKey(Integer.parseInt(busId));
		Busorder busorder = busOrderService.selectByPrimaryKey(buses.getBusorderid());
		
		/*
		 * if (busorder.getDeparturedate().getTime()<new Date().getTime()) {
		 * result.put("status", 1002); result.put("message", "票已使用,无法退票!!");
		 * return Utility.gson.toJson(result); }
		 */
//		if (busorder.getDeparturedate().getTime() < new Date().getTime() + 1000 * 60 * Constants.RefundStopMins) {
//			result.put("status", 1002);
//			result.put("message", "开车前" + Constants.RefundStopMins + "分钟不许退票,请珍惜所内资源,慎重订票!!");
//			return Utility.gson.toJson(result);
//		}
		if (Integer.parseInt(seatNumber) > 49 || Integer.parseInt(seatNumber) < 1) {
			result.put("status", 1002);
			result.put("message", "座号超出限制");
			return Utility.gson.toJson(result);
		}

		int num = ticketOrderService.deleteByPrimaryKey(Integer.parseInt(ticketId));
		if (num == 1) {
		//	buses.setOccupation((short) (buses.getOccupation() - 1));
			busesService.seatOccupationRemove1(buses.getId());
		//	busorder.setOccupation((short) (busorder.getOccupation() - 1));
			busOrderService.seatOccupationRemove1(busorder.getId());
			if (staff.getName().equals(seatName)) {
				staff.setOwncount(staff.getOwncount() - 1);
			} else {
				staff.setRelativecount(staff.getRelativecount() - 1);
			}
			staff.setLastrefunddate(new Date());
			staff.setRefundcount(staff.getRefundcount() + 1);
		//	busesService.updateByPrimaryKeySelective(buses);
		//	busOrderService.updateByPrimaryKeySelective(busorder);
			staffService.updateByPrimaryKey(staff);
			Refundlog refundlog = new Refundlog();
			refundlog.setBusesid(buses.getId());
			refundlog.setStaffid(staff.getId());
			refundlog.setSeatname(seatName);
			refundlog.setSeatnumber(Byte.parseByte(seatNumber));
			refundlog.setReason(cancelReason);
			refundLogService.insertSelective(refundlog);
			result.put("status", 1001);
			result.put("message", "退票成功");
			return Utility.gson.toJson(result);
		} else {
			result.put("status", 1002);
			result.put("message", "退票失败!");
			return Utility.gson.toJson(result);
		}
	}

	/*
	 * 根据车次车辆的id 获取座位的乘坐情况
	 */
	@RequestMapping(value = "getInfoByBusId", method = RequestMethod.POST, produces = {
			"application/json;charset=utf-8" })
	@ResponseBody
	public String getInfoByBusId(@RequestBody Map<String, Integer> args) {
		Map<String, Object> result = new HashMap<>();
		Integer busId = args.get("busId");
		List<Map<String, Object>> ticketInfos = ticketOrderService.getInfoByBusId(busId);
		if (ticketInfos.isEmpty()) {
			result.put("status", 1002);
			return Utility.gson.toJson(result);
		}
		result.put("status", 1001);
		result.put("body", ticketInfos);
		return Utility.gson.toJson(result);
	}

	/*
	 * 获取一辆车的剩余的车位号码 换座用
	 */
	@RequestMapping(value = "getSeatsNumberLeft", method = RequestMethod.POST, produces = {
			"application/json;charset=utf-8" })
	@ResponseBody
	public String getSeatsNumberLeft(@RequestBody Map<String, Integer> args) {
		Map<String, Object> result = new HashMap<>();
		Integer busId = args.get("busId");
		Buses buses=busesService.selectByPrimaryKey(busId);
	//	int busseats[]=new int[buses.getSeatcount()];
		List<Integer> leftseats=new ArrayList<>();
		for (int i = 1; i < buses.getSeatcount()+1; i++) {
			
			leftseats.add(i);
		}
		
		
		List<Map<String, Object>> ticketInfos = ticketOrderService.getInfoByBusId(busId);
		
		for (Map<String, Object> ticketInfo : ticketInfos) {
		Integer ticketNumber=(Integer) ticketInfo.get("seatNumber");
		leftseats.remove(ticketNumber);
		}
		if (ticketInfos.isEmpty()) {
			result.put("status", 1002);
			return Utility.gson.toJson(result);
		}
		result.put("status", 1001);
		result.put("body", leftseats);
		return Utility.gson.toJson(result);
	}

	// 根据员工号获取已定未使用车票
	@RequestMapping(value = "getValidateTicketsInfoByStaffId", method = RequestMethod.POST, produces = {
			"application/json;charset=utf-8" })
	@ResponseBody
	public String getValidateTicketsInfoByStaffId(@RequestBody Map<String, Integer> args) {
		Map<String, Object> result = new HashMap<>();
		Integer staffId = args.get("staffId");
		List<Map<String, Object>> ticketInfos = ticketOrderService.getValidateTicketsInfoByStaffId(staffId);
		if (ticketInfos.isEmpty()) {
			result.put("status", 1002);
			return Utility.gson.toJson(result);
		}
		result.put("status", 1001);
		result.put("body", ticketInfos);
		return Utility.gson.toJson(result);
	}

	/*
	 * 根据员工号获取已使用的车票
	 */
	@RequestMapping(value = "getInvalidateTicketsInfoByStaffId", method = RequestMethod.POST, produces = {
			"application/json;charset=utf-8" })
	@ResponseBody
	public String getInvalidateTicketsInfoByStaffId(@RequestBody Map<String, Integer> args) {
		Map<String, Object> result = new HashMap<>();
		Integer staffId = args.get("staffId");
		List<Map<String, Object>> ticketInfos = ticketOrderService.getInvalidateTicketsInfoByStaffId(staffId);
		if (ticketInfos.isEmpty()) {
			result.put("status", 1002);
			return Utility.gson.toJson(result);
		}
		result.put("status", 1001);
		result.put("body", ticketInfos);
		return Utility.gson.toJson(result);
	}

	/*
	 * 更换车票
	 **/
	@RequestMapping(value = "changeTicketInfo", method = RequestMethod.POST, produces = {
			"application/json;charset=utf-8" })
	@ResponseBody
	public String changeTicketInfo(@RequestBody Map<String, Integer> args) {
		Map<String, Object> result = new HashMap<>();
		Integer staffId = (Integer) args.get("staffId");
		Integer ticketId = (Integer) args.get("ticketId");
		Integer newBusId = (Integer) args.get("newBusId");
		int newSeatNumber = (Integer) args.get("newSeatNumber");
		Ticketorder ticket = ticketOrderService.selectByPrimaryKey(ticketId);
		Buses busold = busesService.selectByPrimaryKey(ticket.getBusesid());
		Buses busnew = busesService.selectByPrimaryKey(newBusId);
		if (busold.getBusorderid().intValue()!=busnew.getBusorderid().intValue()) {
			result.put("status", 1002);
			result.put("message", "出错,非同一方向!");
			return Utility.gson.toJson(result);
		}
		if (busold.getNumber()>8) {
			result.put("status", 1002);
			result.put("message", "出错,登记车不允许换车操作!");
			return Utility.gson.toJson(result);
		}
		if (!ticket.getStaffid().equals(staffId)) {
			result.put("status", 1002);
			result.put("message", "出错,非登录用户所订票,无权修改!");
			return Utility.gson.toJson(result);
		}
		ticket.setBusesid(newBusId);
		ticket.setSeatnumber((byte) newSeatNumber);
		
		Busorder busorder=busOrderService.selectByPrimaryKey(busold.getBusorderid());
		if (busorder.getEndbusdate().getTime()>(new Date()).getTime()) {			//车辆自增截至之前
			result.put("status", 1002);
			result.put("message", "未到换票时间!");
			return Utility.gson.toJson(result);
		}
		else if((busorder.getDeparturedate().getTime()-1000*60*30)>(new Date()).getTime()){//在发车前半个小时
			if (ticket.getChangecount()>0) {
				result.put("status", 1002);
				result.put("message", "此时间内已达到最大换票次数,请发车前半小时再更换!");
				return Utility.gson.toJson(result);
			}
		}
		else if (busorder.getDeparturedate().getTime()<(new Date()).getTime()) {//车辆已开
			result.put("status", 1002);
			result.put("message", "已过换票时间!");
			return Utility.gson.toJson(result);
		}
		else if((busorder.getDeparturedate().getTime()-1000*60*30)<(new Date()).getTime()){//发车前半个小时内
			if (ticket.getChangecount()<2) {
				int num = ticketOrderService.updateByPrimaryKeySelective(ticket);
				if (num == 1) {
					ticket.setChangecount((byte) (ticket.getChangecount()+1));
				//	busold.setOccupation((short) (busold.getOccupation() - 1));
				//	busnew.setOccupation((short) (busnew.getOccupation() + 1));
					busesService.seatOccupationRemove1(busold.getId());
					busesService.seatOccupationAdd1(busnew.getId());
					//busesService.updateByPrimaryKeySelective(busold);
					//busesService.updateByPrimaryKeySelective(busnew);
					ticketOrderService.updateByPrimaryKeySelective(ticket);
					result.put("status", 1001);
				} else {
					result.put("status", 1002);
					result.put("message", "更换车座失败!");
				}
				return Utility.gson.toJson(result);
			}
			else {
				result.put("status", 1002);
				result.put("message", "此票已达到最大换票次数!");
				return Utility.gson.toJson(result);
			}
		}
		else {
			
		}
		int num = ticketOrderService.updateByPrimaryKeySelective(ticket);
		if (num == 1) {
			ticket.setChangecount((byte) (ticket.getChangecount()+1));
		//	busold.setOccupation((short) (busold.getOccupation() - 1));
		//	busnew.setOccupation((short) (busnew.getOccupation() + 1));
			busesService.seatOccupationRemove1(busold.getId());
			busesService.seatOccupationAdd1(busnew.getId());
		//	busesService.updateByPrimaryKeySelective(busold);
		//	busesService.updateByPrimaryKeySelective(busnew);
			ticketOrderService.updateByPrimaryKeySelective(ticket);
			result.put("status", 1001);
		} else {
			result.put("status", 1002);
			result.put("message", "更换车座失败!");
		}
		return Utility.gson.toJson(result);		
		
	}
	

}
